package cn.shop.cloud.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: shop-parent
 * @ClassName CookieUtil
 * @description:
 * @author: Mokio
 * @create: 2024−12-24 10:19
 * @Version 2024 2.2 ; jdk1.8.0_181
 **/
// Cookie存取工具类
public class CookieUtil {

    public static  final String TOKEN_COOKIE_NAME="userToken";
    public static  final int TOKEN_EXPIRE_TIME =1800;

    // 添加cookie,需要的信息包括cookie名称，cookie值，cookie过期时间，注意是response
    public static void addCookie(HttpServletResponse response,String cookieName,String cookieValue,int expireSeconds){
        Cookie cookie = new Cookie(cookieName, cookieValue);

        //设置域
        cookie.setDomain("localhost");
        //设置路径
        cookie.setPath("/");
        //设置过期时间
        cookie.setMaxAge(expireSeconds);

        //将cookie添加到响应中
        response.addCookie(cookie);
    }

    // 获取cookie，需要的参数包括cookie名称，注意是request
    public static String getCookie(HttpServletRequest request, String cookieName){
        // 获取所有cookie
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            for(Cookie cookie:cookies){
                // 判断cookie名称是否一致
                if(cookie.getName().equals(cookieName)){
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

}
